import api from '@/api'
import consts from '@/const'
import { deepCopy, setPage } from '@/utils/util'
import fetch from '@/utils/network/fetch'

const initPage = {
    size: 10,
    number: 0,
    total: 0,
    pages: 0,
    filter: {
        enabled: null,
        name: null
    }
}

const state = {
    data: {
        counters: []
    },
    ui: {
        page: deepCopy(initPage)
    }
}

// getters
const getters = {
    counters: state => state.data.counters,
    counterTotal: state => state.ui.page.total
}

// actions
const actions = {
    getCounters({ commit }, page) {
        fetch('/api/counter', {
            loading: true,
            success: res => {
                const { pages, total, content } = res
                commit('setCounterPage', {
                    pages,
                    total
                })
                commit('setCounters', { content })
            },
            method: 'post',
            data: page ? page : state.ui.page
        })
    },
    saveCounter({ dispatch }, data) {
        fetch('/api/counter', {
            success: () => dispatch('getCounters'),
            method: 'put',
            data
        })
    }
}

// mutations
const mutations = {
    setCounters: (state, payload) => {
        state.data.counters = payload.content
    },
    setCounterPage: (state, page) => {
        page && setPage(state.ui.page, page)
    }
}

export default {
    state,
    getters,
    actions,
    mutations
}
